package com.zby.business.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.zby.business.R;
import com.zby.business.adapter.DetailViewPagerAdapter;
import com.zby.business.net.MyAsyncTask;
import com.zby.business.util.App;
import com.zby.business.util.Util;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.concurrent.ExecutionException;

/**
 * Created by BY on 2016/3/7.
 */
public class Detail extends Activity implements View.OnClickListener {
    private TextView nameTextView, priceTextView, priceTextView1, saleTextView, detailTextView, commentTextView, addToCarTextView, purchaseTextView;
    private ViewPager viewPager;
    private LinearLayout detailLayout;
    private String id, price;
    private String[] urls;
    private ArrayList comments;
    private LayoutInflater inflater;
    private ImageView backImageView;
    private App app;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.detail);
        initView();
        ininData();
        DetailViewPagerAdapter adapter = new DetailViewPagerAdapter(getApplicationContext(), urls);
        viewPager.setAdapter(adapter);
        super.onCreate(savedInstanceState);
    }

    private void ininData() {
        comments = new ArrayList();
        Bundle bundle = getIntent().getExtras().getBundle("bundle");
        price = bundle.get("price") + "";
        String[] name = bundle.get("price").toString().split("\\.");
        priceTextView.setText(name[0] + ".");
        priceTextView1.setText(name[1]);
        nameTextView.setText(bundle.get("introduce") + "");
        saleTextView.setText("销量:" + bundle.get("sale"));
        id = bundle.get("commodityId") + "";
        urls = bundle.get("url").toString().split("\\;");
    }

    private void initView() {
        app = (App) getApplication();
        inflater = LayoutInflater.from(getApplicationContext());
        addToCarTextView = (TextView) findViewById(R.id.addToCarTextView);
        purchaseTextView = (TextView) findViewById(R.id.purchaseTextView);
        priceTextView = (TextView) findViewById(R.id.detailPriceTextView);
        priceTextView1 = (TextView) findViewById(R.id.detailPriceTextView1);
        nameTextView = (TextView) findViewById(R.id.detailNameTextView);
        saleTextView = (TextView) findViewById(R.id.detailSaleTextView);
        detailTextView = (TextView) findViewById(R.id.detailTextView);
        commentTextView = (TextView) findViewById(R.id.commentTextView);
        backImageView = (ImageView) findViewById(R.id.back);
        viewPager = (ViewPager) findViewById(R.id.detailViewPager);
        detailLayout = (LinearLayout) findViewById(R.id.detailLinearLayout);
        addToCarTextView.setOnClickListener(this);
        backImageView.setOnClickListener(this);
        purchaseTextView.setOnClickListener(this);
        commentTextView.setOnClickListener(this);
        detailTextView.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.commentTextView:
                detailTextView.setBackgroundColor(getResources().getColor(R.color.lightGrey));
                commentTextView.setBackgroundColor(getResources().getColor(R.color.gray));
                loadComment();
                break;
            case R.id.detailTextView:
                commentTextView.setBackgroundColor(getResources().getColor(R.color.lightGrey));
                detailTextView.setBackgroundColor(getResources().getColor(R.color.gray));
                detailLayout.removeAllViews();
                break;
            case R.id.back:
                finish();
                break;
            case R.id.addToCarTextView:
                if (isLogin()) {
                    addToCar();
                } else {
                    jumpAlert();
                }
                break;
            case R.id.purchaseTextView:
                if (isLogin()) {
                    purchase();
                } else {
                    jumpAlert();
                }
                break;
        }

    }

    private void jumpAlert() {
        AlertDialog.Builder alert = new AlertDialog.Builder(Detail.this);
        alert.setMessage("登录后才可以进行该操作!");
        alert.setPositiveButton("去登录", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(Detail.this, Login.class);
                startActivity(intent);
            }
        });
        alert.setNegativeButton("知道了", null);
        alert.show();
    }

    private boolean isLogin() {
        if (!app.getUserId().equals("") && !app.getName().equals("")) {
            return true;
        } else {
            return false;
        }
    }

    private void purchase() {
        View view = inflater.inflate(R.layout.confirm, null);
        final AlertDialog alert = new AlertDialog.Builder(Detail.this, AlertDialog.THEME_HOLO_LIGHT).create();
        final Button subButton = (Button) view.findViewById(R.id.subButton);
        Button addButton = (Button) view.findViewById(R.id.addButton);
        Button cofirmButton = (Button) view.findViewById(R.id.cofirmButton);
        final EditText numberEditText = (EditText) view.findViewById(R.id.numberEditText);
        final int[] number = {Integer.parseInt(numberEditText.getText().toString())};
        subButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                number[0] = Integer.parseInt(numberEditText.getText().toString());
                numberEditText.setText(number[0] - 1 + "");
                if (number[0] == 2) {
                    subButton.setClickable(false);
                }
            }
        });
        addButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                number[0] = Integer.parseInt(numberEditText.getText().toString());
                numberEditText.setText(number[0] + 1 + "");
                if (number[0] > 1) {
                    subButton.setClickable(true);
                }
            }
        });
        cofirmButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (app.getAccount() - number[0] * Float.parseFloat(price) < 0) {
                    Util.toast(getApplicationContext(), "钱不够");
                } else {
                    MyAsyncTask asyncTask = new MyAsyncTask();
                    try {
                        String s = asyncTask.execute("phonePurchase?detailId=" + id + "&userId=" + app.getUserId() + "&price=" + Float.parseFloat(price) * Integer.parseInt(numberEditText.getText().toString()) + "&number=" + numberEditText.getText().toString()).get();
                        if (s.equals("success")) {
                            Util.toast(getApplicationContext(), "操作成功");
                            app.setAccount(app.getAccount() - number[0] * Float.parseFloat(price));
                        } else {
                            Util.toast(getApplicationContext(), "出问题了");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        Util.toast(getApplicationContext(), "出问题了");
                    }
                    alert.dismiss();
                }
            }
        });
        alert.setView(view);
        alert.show();
    }

    private void addToCar() {
        MyAsyncTask asyncTask = new MyAsyncTask();
        try {
            String s = asyncTask.execute("phoneAddToCar?detailId=" + id + "&userId=" + app.getUserId() + "&price=" + price + "&number=1").get();
            if (s.equals("success")) {
                Util.toast(getApplicationContext(), "保存成功");
            } else {
                Util.toast(getApplicationContext(), "保存失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            Util.toast(getApplicationContext(), "保存失败");
        }
    }

    private void loadComment() {
        if (comments.size() == 0) {
            MyAsyncTask asyncTask = new MyAsyncTask();
            try {
                String s = asyncTask.execute("phoneComment?detailId=" + id).get();
                System.out.println(s);
                JSONObject commentJsonObject = new JSONObject(s);
                JSONArray commentArray = commentJsonObject.getJSONArray("comments");
                if (commentArray.length() > 0) {
                    for (int i = 0; i < commentArray.length(); i++) {
                        JSONObject comment = (JSONObject) commentArray.get(i);
                        comments.add(comment.get("content"));
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
                comments.add("还没有评价哦");
            }
        }
        detailLayout.removeAllViews();

        final View view = inflater.inflate(R.layout.addcomment, null);
        final LinearLayout addCommentLayout = (LinearLayout) view.findViewById(R.id.addCommentLayout);
        final Button commentButton = (Button) view.findViewById(R.id.commentButton);
        final EditText addCommentEdit = (EditText) view.findViewById(R.id.addCommentEdit);
        ImageView addCommentImage = (ImageView) view.findViewById(R.id.addCommentImage);
        commentButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MyAsyncTask asyncTask = new MyAsyncTask();
                try {
                    String s = asyncTask.execute("phoneCheckOrder?detailId=" + id + "&userId=" + app.getUserId()).get();
                    System.out.println("check   " + s);
                    if (s.equals("success")) {
                        commentButton.setVisibility(View.GONE);
                        addCommentLayout.setVisibility(View.VISIBLE);
                    } else if (s.equals("fail")) {
                        Util.toast(getApplicationContext(), "没买不能评论哦");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Util.toast(getApplicationContext(), "出错了");
                }
            }
        });
        addCommentImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String c = addCommentEdit.getText().toString().trim();
                String content = c.replace(" ", "+");
                if (content.equals("")) {
                    commentButton.setVisibility(View.VISIBLE);
                    addCommentLayout.setVisibility(View.GONE);
                } else {
                    MyAsyncTask asyncTask = new MyAsyncTask();
                    try {
                        String s = asyncTask.execute("phoneAddComment?detailId=" + id + "&userId=" + app.getUserId() + "&content=" + content).get();

                        if (s.equals("success")) {
                            commentButton.setVisibility(View.VISIBLE);
                            addCommentLayout.setVisibility(View.GONE);
                            addCommentEdit.setText("");
                            comments.add(c);
                            TextView textView = new TextView(getApplicationContext());
                            textView.setPadding(30, 30, 30, 30);
                            textView.setText(c + "");
                            textView.setTextColor(Color.BLACK);
                            detailLayout.addView(textView, detailLayout.getChildCount() - 1);
                        } else if (s.equals("fail")) {
                            Util.toast(getApplicationContext(), "出错了");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        for (Object comment : comments) {
            TextView textView = new TextView(getApplicationContext());
            textView.setPadding(30, 30, 30, 30);
            textView.setText(comment + "");
            textView.setTextColor(Color.BLACK);
            detailLayout.addView(textView);
        }
        detailLayout.addView(view);
    }
}
